// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;

namespace SnapObjects.Data
{
    internal class SqlWhereCondition : SqlWhereAndOr<ISqlWhereCondition>, ISqlWhereCondition
    {
        private readonly SqlConditionBuilder _cbuilder;

        public SqlWhereCondition(bool isEmbedded)
            : this(new SqlConditionBuilder(SqlConditionType.Where, isEmbedded))
        {

        }

        private SqlWhereCondition(SqlConditionBuilder builder)
            : base(builder, ((ConditionStatement)builder.Statement).Condition)
        {
            _cbuilder = (SqlConditionBuilder)_builder;
        }

        public ISqlWhereCondition Create(
            string clause, ISqlParameter[] parameters, string builderAlias)
        {
            _cbuilder.AddParameters(parameters);

            if (!String.IsNullOrWhiteSpace(clause))
            {
                _cbuilder.Condition.Condition.Add(new WhereElement(clause, builderAlias));
            }

            return this;
        }

        public ISqlWhereCondition Create(
            string left,
            SqlOperator sqlOperator,
            object right,
            SqlRightType rightType,
            params ISqlParameter[] parameters)
        {
            this.Create(left, sqlOperator, right, rightType, true, parameters);

            return this;
        }

        public ISqlWhereCondition Create(
            string left,
            SqlOperator sqlOperator,
            object right,
            SqlRightType rightType,
            bool isUnaided,
            params ISqlParameter[] parameters)
        {
            if (parameters.Length > 0)
            {
                _cbuilder.AddParameters(parameters);
            }

            if (rightType == SqlRightType.Parameter
                && right is ISqlParameter parameter)
            {
                _clause.AddParameter(parameter);
            }

            var condition = new ConditionElement(left, sqlOperator, right, rightType, "", isUnaided);

            _clause.Add(new WhereElement(condition));

            return this;
        }

        public SqlBuildClause Clause => _clause;
        public ISqlParameter[] BuilderParameters => _cbuilder.Condition.Parameters;
        protected override ISqlWhereCondition BuilderResult()
        {
            return this;
        }
    }
}
